import { ConfigEnum } from '@/common/enum/config.enum';
import { RedisCommonService } from '@/common/redis/redis.service';
import { comparePassword } from '@/common/utils/bcrypt';
import { saveLocalDate } from '@/common/utils/moment';
import { Cache, CACHE_MANAGER } from '@nestjs/cache-manager';
import { BadRequestException, Inject, Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { JwtService } from '@nestjs/jwt';
import { UsersService } from './../users/users.service';
import { LoginDto } from './dto/login.dto';

@Injectable()
export class AuthService {
  constructor(
    // @InjectRepository(SysUser)
    // private readonly userRepository: Repository<SysUser>,
    @Inject(CACHE_MANAGER) private cacheManager: Cache,
    // @InjectRedis() private readonly redis: Redis,
    private readonly redis: RedisCommonService,
    private readonly usersService: UsersService,
    private readonly jwtService: JwtService,
    private readonly configService: ConfigService,
  ) {}

  async getCaptcha() {
    await this.cacheManager.set('key', 'value');
    const value = await this.cacheManager.get('key');

    console.log(
      '🚀 ~ auth.service.ts:25 ~ AuthService ~ getCaptcha ~ value:',
      value,
    );

    console.log(await this.redis.get('hello'));
    return 'This action returns a captcha';
  }
  async login(body: LoginDto) {
    console.log('🚀 ~ auth.service.ts:39 ~ AuthService ~ login ~ body:', body);

    const user = await this.usersService.findOneByUsername(body.username);

    if (!user) throw new BadRequestException('用户不存在');
    const visPwd = await comparePassword(user.password, body.password);
    if (!visPwd) {
      throw new BadRequestException('用户名或密码错误');
    }

    // _.omit(user, ['password']); // 去除密码
    const { password: _password, sysRoles, dept, ...userInfo } = user;
    const payload = Object.assign({}, userInfo);

    payload.dataScoupe = 3;
    payload.authorities = [];
    payload.roleIds = [];
    payload.deptName = dept.name;
    payload.roleNames = [];

    payload.authorities = sysRoles.map((role) => {
      if (role.dataScope < payload.dataScope) {
        payload.dataScope = role.dataScope;
      }
      payload.roleIds.push(role.id);
      payload.roleNames.push(role.name);
      return `ROLE_${role.code}`;
    });

    payload.updateTime = saveLocalDate(payload.updateTime);
    payload.createTime = saveLocalDate(payload.createTime);

    return {
      accessToken: await this.jwtService.signAsync(payload),
      refreshToken: await this.jwtService.signAsync(payload, {
        expiresIn:
          Number(this.configService.get(ConfigEnum.JWT_EXPIRES_IN)) * 2,
      }),
      expiresIn: Number(this.configService.get(ConfigEnum.JWT_EXPIRES_IN)),
      tokenType: 'Bearer',
    };
  }

  register() {
    return 'This action returns a token';
  }

  logout() {
    // 验证Token失效(在用户发起退出登录请求时，服务端首先验证Token的有效性。如果Token无效或已过期，直接返回错误信息。)

    // 清除Redis中的会话信息(如果Token有效，服务端需要在Redis中查找并删除与该Token相关的所有会话信息。这可以通过查询Redis中的键值对来实现，并删除与该Token相关的所有条目。)

    // 更新状态‌(在Redis中清除会话信息后，服务端还需要更新数据库中的用户状态，标记用户已经退出登录。这可以通过更新数据库中的相应字段来实现。)

    // ‌返回响应(服务端应向客户端返回一个成功的响应，表示用户已经成功退出登录。这通常是一个包含成功信息的HTTP响应。)

    // res.clearCookie('connect.sid'); // connect.sid 是默认的 Session Cookie 名称
    // res.clearCookie('sessionId');
    return '退出成功';
  }
}
